package io.p2p.stream.turn.task;

import io.p2p.stream.turn.node.ActiveNode;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Iterator;
import java.util.Map;

/**
 * 客户端节点心跳检测
 */
@Slf4j
public class ActiveNodeHeartbeatMonitorTask implements Runnable {
    private Map<String, ActiveNode> activeNodeMap;
    public ActiveNodeHeartbeatMonitorTask(Map<String, ActiveNode> activeNodeMap){
         this.activeNodeMap = activeNodeMap;
    }

    @Override
    public void run() {
        //遍历在线客户端列表，检查心跳状态
        Iterator<ActiveNode> it = activeNodeMap.values().iterator();
        while(it.hasNext()){
            ActiveNode node = it.next();
            Date currentTime = new Date();
            //如果客户端超过一定时间没有心跳，标记为离线并从列表中删除
            //假设10秒没有心跳则视为离线
            if(currentTime.getTime() - node.getLastActiveTime().getTime() > 10 * 1000){
                log.info("Client Node at IP: {},Port: {},Name: {} is offline.",
                        node.getIp(),node.getPort(),node.getName());
                it.remove();
            }
        }
    }
}
